package com.imy.luascript.retrofit.factory;

import com.imy.luascript.helper.UrlHelper;
import com.imy.luascript.retrofit.OkHttpProvider;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 在此写用途
 *
 * @author: Imy
 * @date: 2017-03-06
 */
public class RetrofitFactory {

  private OkHttpClient mOkHttpClient;
  private Retrofit mRetrofit;
  private int mTimeOut; //超时时间 秒为单位

  private RetrofitFactory() {

    mOkHttpClient = OkHttpProvider.getOkHttpClient();
  }

  public static RetrofitFactory getInstance() {
    return SingletonHolder.INSTANCE;
  }

  public static RetrofitFactory getNoCacheInstance() {
    RetrofitFactory factory = SingletonHolder.INSTANCE;
    factory.mOkHttpClient = OkHttpProvider.getOkHttpClient();
    return factory;
  }


  public <T> T getService(Class<T> serviceClass) {
    return createService(serviceClass, UrlHelper.DOMAIN);
  }
  public <T> T getService(Class<T> serviceClass, String baseUrl) {
    return createService(serviceClass, baseUrl);
  }

  public <T> T getService(Class<T> serviceClass, String baseUrl, int timeOut) {
    if(mRetrofit == null || mTimeOut != timeOut){
      mTimeOut = timeOut;
      mRetrofit = new Retrofit.Builder()
          .baseUrl(baseUrl)
          .client(OkHttpProvider.getOkHttpClient(timeOut))
          .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
          .addConverterFactory(GsonConverterFactory.create())
          .build();
    }
    return mRetrofit.create(serviceClass);
  }

  private <T> T createService(Class<T> serviceClass, String baseUrl) {
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(baseUrl)
        .client(mOkHttpClient)
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .build();
    return retrofit.create(serviceClass);
  }

  private static class SingletonHolder {
    private static final RetrofitFactory INSTANCE = new RetrofitFactory();
  }
}
